﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tilver.Configuration;
using Tilver.Configuration.Logging;

namespace Tilver.Common
{
    public class LoggerFactory
    {
        private static Dictionary<string, ILogger> _loggerCache = new Dictionary<string, ILogger>();
        private static object _lock = new object();
        /// <summary>
        /// 创建ILogger对象
        /// </summary>
        /// <param name="categoryName">配置文件tinver.logging.categorys中定义的categoryName</param>
        /// <returns></returns>
        public static ILogger Create(string categoryName = null)
        {
            categoryName = categoryName ?? string.Empty;
            if (!_loggerCache.ContainsKey(categoryName))
            {
                TilverSection section = TilverSection.GetSection();
                if (section == null)
                {
                    throw new Exception("配置文件中不存在tilver配置节定义。");
                }
                LoggingConfigElement loggingConfig = section.LoggingConfig;
                if (string.IsNullOrEmpty(categoryName))
                {
                    categoryName = loggingConfig.DefaultCategory;
                }
                if (string.IsNullOrEmpty(categoryName))
                {
                    throw new ArgumentException("categoryName不能为空，请设置DefaultCategory或tilver.logging.categorys中存在的categoryName定义。", "categoryName");
                }
                lock (_lock)
                {
                    if (!_loggerCache.ContainsKey(categoryName))
                    {
                        ILogger logger = new Logger(categoryName);
                        _loggerCache.Add(categoryName, logger);
                    }
                }
            }
            return _loggerCache[categoryName];
        }
    }
}
